<?php

namespace Web\MainSiteBundle\Controller;


use Model\MessageBundle\Entity\Message;
use Model\MessageBundle\Model\MessageModel;
use Model\UserBundle\Model\UserLoginLogModel;
use Model\UserBundle\Model\UserModel;
use Model\UserBundle\Setting\UserSetting;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;

class UserController extends WebBaseController
{
    /**
     * @route("user/index",name="WebUserIndex")
     */
    public function WebUserIndexAction()
    {//测试角色用的
        $user = $this->needToBeUser();
        $data = array("user" => $user);
        return $this->render("WebMainSiteBundle:User:user_index.html.twig",$data);
    }
    /**
     * @route("user/reg",name="WebUserReg")
     */
    public function WebUserRegAction(Request $request)
    {
        $userModel = new UserModel($this->getDoctrine());
        if ($request->getMethod("POST") == "POST") {
            //处理账号
            if (!$account = $this->getParamRequired("account")) {return $this->js_out("请输入账号");}
            if (strlen($account) < 6) {return $this->js_out("账号长度应大于6位");}
            if ($userModel->checkAccountForNew($account)) {return $this->js_out("账号已被使用，请尝试其他账号");}
            //处理密码
            if (!$password = $this->getParamRequired("password")) {return $this->js_out("请输入密码");}
            if (strlen($password) < 6) {return $this->js_out("密码长度应大于6位");}
            if (!$passwordAgain = $this->getParamRequired("passwordAgain")) {return $this->js_out("请输入确认密码");}
            if ($password !== $passwordAgain) {return $this->js_out("两次输入的密码不一致");}
            //处理验证码
            if (!$captcha = $this->getParamRequired("captcha")) {return $this->js_out("请输入验证码");}
            $session = $request->getSession();
            $sessionCaptcha = $session->get("captcha");
            if (strtolower($captcha) != $sessionCaptcha || $sessionCaptcha == "") {return $this->js_out("验证码错误$sessionCaptcha"."$captcha");}

            //新增记录
            $params = array(
                "account"   => $account,
                "password"  => md5($password),
                "passwordPay"  => md5($password),
                "groups"  => 3,
            );
            //推荐人处理
            $userSettings = new UserSetting($this->getDoctrine()) ;
            $key = $userSettings->inviteUrlKey;
            $field = $userSettings->inviteSetKey;
            if ( $parent = $this->getParamRequired($key) )
            {//推荐人获取到了，并且核对有此用户
                $params["$field"] = $parent;
            }
            if ($userModel->commReg($params)) {
                return $this->js_out("注册成功",$this->generateUrl("WebUserReg"));
            } else {
                return $this->js_out("系统出错，注册失败",$this->generateUrl("WebUserReg"));
            }
        } else {
            //表单创建
            return $this->render("WebMainSiteBundle:User:user_reg.html.twig");
        }
    }


    /**
     * @route("user/login",name="WebUserLogin")
     */
    public function WebUserLoginAction(Request $request)
    {
        $session = $request->getSession();
        $lastUserName = $session->get(Security::LAST_USERNAME) ? $session->get(Security::LAST_USERNAME) : "";
        if ($lastUserName) {
            //todo 参数检查应该更细致一些
            $message = "账号或者密码错误";
        } else {
            $message = "";
        }
        return $this->render("WebMainSiteBundle:User:user_login.html.twig",array(
            "lastUser"  => $lastUserName,
            "message"   => $message
        ));
    }

    /**
     * @route("user/login/log",name="WebUserLoginLog")
     */
    public function UserLoginLogAction(){
        $userLoginLog = new UserLoginLogModel($this->getDoctrine());
        if ($user = $this->getUser()) {
            $loginInfo = $userLoginLog->createLoginLogInfo($user);
        } else {
            $loginInfo = $userLoginLog->createLoginLogInfo();
        }
        $userLoginLog->addLoginLog($loginInfo);
        return $this->redirectToRoute("WebUserIndex");
    }

    /**
     * @route("user/info",name="WebUserInfo")
     */
    public function WebUserInfoAction(Request $request)
    {
        $user = $this->needToBeUser();
        $userModel = New UserModel($this->getDoctrine());
        $uid = $user->getId();
        if ($request->getMethod("POST") == "POST")
        {//更新账号信息
            if (!$nickName = $this->getParamRequired("nickName")) {return $this->js_out("请输入昵称");}
            if (!$email = $this->getParamRequired("email")) {return $this->js_out("请输入email");}
            if (!$phone = $this->getParamRequired("phone")) {return $this->js_out("请输入手机号");}
            $data = array();
            $data["nickName"] = $nickName;
            $data["email"] = $email;
            $data["phone"] = $phone;
            $userModel->updateUserInfo($uid,$data);
        }
        $userInfo = $userModel->getUserInfo($uid);
        $data = array("user" => $userInfo);
        return $this->render("WebMainSiteBundle:User:user_info.html.twig",$data);
    }

    /**
     * @route("user/password",name="WebUserPassword")
     */
    public function WebUserPasswordAction(Request $request)
    {
        $user = $this->needToBeUser();
        $userModel = New UserModel($this->getDoctrine());
        $uid = $user->getId();
        if ($request->getMethod("POST") == "POST")
        {//更新账号信息
            if (!$oldPassword = $this->getParamRequired("oldPassword")) {return $this->js_out("请输入原密码");}
            if ($user->getPassword() != md5($oldPassword)) {return  $this->js_out("请输入正确的原密码");}
            if (!$newPassword = $this->getParamRequired("newPassword")) {return $this->js_out("请输入新密码");}
            if (strlen($newPassword) < 6) {return $this->js_out("请设置6位以上新密码");}
            $newPasswordAgain = $this->getParamRequired("newPasswordAgain");
            if ($newPasswordAgain !== $newPassword ) {return $this->js_out("两次输入的新密码不一致");}
            $data = array();
            $data["password"] = md5($newPassword);
            $userModel->updateUserInfo($uid,$data);
        }
        $userInfo = $userModel->getUserInfo($uid);
        $data = array("user" => $userInfo);
        return $this->render("WebMainSiteBundle:User:user_password.html.twig",$data);
    }

    /**
     * @route("user/headPic",name="WebUserHeadPic")
     */
    public function WebUserHeadPicAction(Request $request)
    {
        $user = $this->needToBeUser();
        $userModel = New UserModel($this->getDoctrine());
        $uid = $user->getId();
        if ($request->getMethod("POST") == "POST")
        {//更新账号信息
            if (!$headPic = $this->getParamRequired("headPic")) {return $this->js_out("您似乎没有选择头像啊？！");}

            $data = array();
            $data["headPic"] = $headPic;
            $userModel->updateUserInfo($uid,$data);
        }
        $userInfo = $userModel->getUserInfo($uid);
        $data = array("user" => $userInfo);
        return $this->render("WebMainSiteBundle:User:user_head_pic.html.twig",$data);
    }


    /**
     * @route("user/roles",name="WebUserRoles")
     */
    public function WebUserRolesAction()
    {//测试角色用的
        $user = $this->needToBeUser();
        $user->getRoles();
        $userId = $user->getId();
        $userModel = new UserModel($this->getDoctrine());
        $roles = $userModel->getUserRolesByUser($userId);
    }

    /**
     * @route("user/messages",name="WebUserMessages")
     */
    public function WebUserMessagesAction()
    {
        $user = $this->needToBeUser();
        $data = array("user" => $user);
        $messageModel = new MessageModel($this->getDoctrine());
        $messages = $messageModel->getListForUser($user->getId());
        $data["messages"] = $messages;
        return $this->render("WebMainSiteBundle:User:user_messages.html.twig",$data);
    }

    /**
     * @route("user/message/{id}",name="WebUserMessageShow")
     */
    public function WebUserMessageShowAction(Message $message)
    {
        $user = $this->needToBeUser();
        $data["message"] = $message;
        return $this->render("WebMainSiteBundle:User:user_message_show.html.twig",$data);
    }

    /**
     * @route("user/mind",name="WebUserMind")
     */
    public function WebUserMind()
    {
        $user = $this->needToBeUser();
        $data["message"] = array();
        return $this->render("WebMainSiteBundle:User:user_mind.html.twig",$data);
    }

    /**
     * @route("user/static",name="WebUserStatistic")
     */
    public function WebUserStatistic()
    {
        $user = $this->needToBeUser();
        $data["message"] = array();
        return $this->render("WebMainSiteBundle:User:user_static.html.twig",$data);
    }
}
